package com.example.demo.httpasyncclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.nio.protocol.BasicAsyncResponseConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestProducer;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;


/**
 * http://hc.apache.org/httpcomponents-asyncclient-dev/examples.html
 *
 * @author Created by niugang on 2020/3/24/9:01
 */
public class AsyncTest2 {

    public static void main(String[] args) throws InterruptedException, IOException {
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        HttpAsyncRequestProducer producer3 = null;
        BasicAsyncResponseConsumer consumer3 = null;
        try {

            httpclient.start();

            // request and response body content
            final CountDownLatch latch2 = new CountDownLatch(1);
            final HttpGet request3 = new HttpGet("http://www.apache.org/");
            producer3 = HttpAsyncMethods.create(request3);
            consumer3 = new BasicAsyncResponseConsumer();
            //定义回调函数
            httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response3) {
                    latch2.countDown();
                    System.out.println(request3.getRequestLine() + "->" + response3.getStatusLine() + " completed");
                }

                @Override
                public void failed(final Exception ex) {
                    latch2.countDown();
                    System.out.println(request3.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch2.countDown();
                    System.out.println(request3.getRequestLine() + " cancelled");
                }

            });
            //  //主线程等待异步线程执行完毕
            latch2.await();
            System.out.println("请求完成");
        } finally {
            httpclient.close();
            if (producer3 != null) {
                producer3.close();
            }
            if (consumer3 != null) {
                consumer3.close();
            }

        }
    }
}
